package cn.javastudy.jdbc.advance;

import static cn.javastudy.jdbc.GlobalProperties.password;
import static cn.javastudy.jdbc.GlobalProperties.url;
import static cn.javastudy.jdbc.GlobalProperties.user;

import cn.javastudy.jdbc.advance.pojo.Employee;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 主键回显
 */
public class IdBackShow {
    public static void main(String[] args) throws SQLException {
        String sql = "INSERT INTO t_emp(emp_name,emp_salary,emp_age) VALUES (?,?,?)";
        try(
            // 获取连接对象
            Connection connection = DriverManager.getConnection(url, user, password);
            // 预编译SQL语句，告知preparedStatement，返回新增数据的主键列的值
            PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        ) {
            preparedStatement.setString(1, "jack");
            preparedStatement.setDouble(2, 123.45);
            preparedStatement.setInt(3, 29);
            int result = preparedStatement.executeUpdate();
            if (result > 0) {
                ResultSet resultSet = preparedStatement.getGeneratedKeys();
                while (resultSet.next()) {
                    System.out.println(resultSet.getString(1));
                }
            }
        }
    }
}
